package com.jf3q.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jf3q.common.domain.EduCourse;
import com.jf3q.common.domain.EduCourseDescription;
import com.jf3q.common.domain.EduTeacher;
import com.jf3q.common.exception.JfException;
import com.jf3q.common.mapper.EduCourseMapper;
import com.jf3q.common.service.EduCourseService;
import com.jf3q.common.service.EduCourseWebDescriptionService;
import com.jf3q.common.vo.CourseInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Service("eduCourseServiceImplCommon") //避免同名bean定义的冲突并使应用能够正常运行
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse>
    implements EduCourseService {
    //课程描述注入
    @Autowired
    private EduCourseWebDescriptionService courseDescriptionService;

    @Override
    public String saveCourse(CourseInfoVo courseInfoVo) {
        //1 向课程表添加课程基本信息
        //CourseInfoVo对象转换eduCourse对象
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int insert = baseMapper.insert(eduCourse);
        if(insert == 0) {
            //添加失败
            throw new JfException(20001,"添加课程信息失败");
        }

        //获取添加之后课程id
        String cid = eduCourse.getId();

        //2 向课程简介表添加课程简介
        //edu_course_description
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        //设置描述id就是课程id
        courseDescription.setId(cid);
        courseDescriptionService.save(courseDescription);

        return cid;
    }

    @Override
    public void del(String id) {
        EduCourse course=new EduCourse();
        course.setId(id);
        baseMapper.del(course);
        if (-2==course.getResult()){

            throw new JfException(50000,"该课程下有章节，删除失败!");
        }
        if (-1==course.getResult()){
            throw new JfException(50000,"该课程下有小节，删除失败!");
        }


    }

    @Override
    public List<EduCourse> selectByTeacherId(EduTeacher teacher) {
        LambdaQueryWrapper<EduCourse>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(EduCourse::getTeacherId,teacher.getId());
        queryWrapper.orderByDesc(EduCourse::getEduModified);
        List<EduCourse> courseList = baseMapper.selectList(queryWrapper);
        return courseList;
    }
}




